package com.example.front.arrange;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ExecutorHelper
 *
 * @author liming2
 * @date 2023/11/7 11:18
 */
public class ExecutorHelper {

    private static ExecutorHelper instance;
    private Map<String, ThreadPoolExecutor> map = new ConcurrentHashMap<String, ThreadPoolExecutor>();

    private ExecutorHelper() {
        instance=this;
    }

    public static ExecutorHelper getInstance() {
        if(null != instance)
            return instance;
        synchronized (ExecutorHelper.class) {
            if(null == instance)
                new ExecutorHelper();
        }
        return instance;
    }
    public ThreadPoolExecutor getExecutor(String name) {
        ThreadPoolExecutor executor = map.get(name);
        if(null == executor){
            synchronized (ExecutorHelper.class) {
                executor = map.get(name);
                if(null == executor) {
                    executor = createExecutor(name);
                    map.put(name, executor);
                }
            }
        }
        return executor;
    }

    public <T> Future<T> execute(String name, Callable<T> callable) {
        ThreadPoolExecutor executor = getExecutor(name);
        Future<T> future = executor.submit(callable);
        return future;
    }

    public void execute(String name, Runnable task){
        ThreadPoolExecutor executor = getExecutor(name);
        executor.execute(task);
    }

    private ThreadPoolExecutor createExecutor(String name) {
        return new ThreadPoolExecutor(10, 10, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
    }
}
